<template>
    <div>
        <!-- 面包屑导肮 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片 -->
        <el-card class="box-card">

            <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning"></el-alert>

            <el-row>
                <el-col><span>选择商品分类：</span>
                    <el-cascader expand-trigger="hover" :options="cateList" :props="cateProps"
                        v-model="selectedCateKeys" @change="cateChange"></el-cascader>
                </el-col>

            </el-row>
            <el-tabs v-model="activeName" @tab-click="tabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
                    <el-table class="manyTable" :data="manyTableData" stripe border>
                        <el-table-column type="expand">
                            <template #default="scope">
                                <el-tag v-for="(attr,i) in scope.row.attr_vals" :key="i" @close="removeTag(i,scope.row)" closable>
                                    {{attr}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 新建
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" />
                        <el-table-column label="参数名称" prop="attr_name" width="300" />
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                    @click="showUpdateDialog(scope.row.attr_id)">修改</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="openDeleteBox(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="isBtnDisabled">添加参数</el-button>
                    <el-table class="onlyTable" :data="onlyTableData" stripe border>
                        <el-table-column type="expand" />
                        <el-table-column type="index" />
                        <el-table-column label="参数名称" prop="attr_name" width="300" />
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>

            </el-tabs>

        </el-card>
        <!-- 添加修改对话框 -->
        <el-dialog :title="this.addUpdateFormOper === 'add'?'添加参数':'修改参数'" :visible.sync="addUpdateDialogVisible"
            width="30%">
            <span>
                <!-- 添加角色表单 -->
                <el-form label-width="85px" class="add_form" :model="addUpdateForm" :rules="addUpdateRules"
                    ref="addUpdateForm">
                    <!-- 参数名 -->
                    <el-form-item label="参数名称" prop="attr_name">
                        <el-input v-model="addUpdateForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogCancle">取 消</el-button>
                <el-button type="primary" @click="dialogOK">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    reqCategory,
    reqParams,
    reqAddParams,
    reqParamsById,
    reqUpdateParamsById,
    reqDeleteParamsById
} from '@/api'
export default {
    created() {
        //发送请求拿到分类列表
        this.getCateList()
    },

    data() {
        return {
            cateList: [],
            cateProps: {
                label: 'cat_name',
                value: 'cat_id',
                children: 'children'
            },
            selectedCateKeys: [],
            // 分页tabs
            activeName: 'many',
            manyTableData: [],
            onlyTableData: [],
            //添加修改对话框
            addUpdateDialogVisible: false,
            addUpdateFormOper: 'add',
            addUpdateForm: {
                attr_name: ''
            },
            addUpdateRules: {
                attr_name: [
                    {
                        required: true,
                        message: '请输入参数名称',
                        trigger: 'blur'
                    }
                ]
            },
            attrId: ''
        }
    },
    computed: {
        isBtnDisabled() {
            return this.selectedCateKeys.length !== 3
        },
        cateId() {
            if (this.selectedCateKeys.length === 3) {
                return this.selectedCateKeys[2]
            }
            return null
        }
    },
    methods: {
        async getCateList() {
            const {
                data,
                meta: { msg, status }
            } = await reqCategory({ type: 3 })
            if (200 !== status) return this.$message.error(msg)

            this.cateList = data
        },
        cateChange() {
          
            this.getParamsData()
        },
        tabClick(tab, event) {
            this.getParamsData()
        },
        async getParamsData() {
            if (this.selectedCateKeys.length !== 3) {
                this.selectedCateKeys = []
                this.manyTableData=[],
                this.onlyTableData=[]
                return
            }
            const {
                data,
                meta: { msg, status }
            } = await reqParams(this.cateId, this.activeName)
            if (200 !== status) return this.$message.error(msg)
            data.forEach((paramsObj) => {
                paramsObj.attr_vals = paramsObj.attr_vals ? paramsObj.attr_vals.split(' ') : []
                paramsObj.inputValue = ''
                paramsObj.inputVisible = false
            })

            if (this.activeName === 'many') {
                this.manyTableData = data
            } else {
                this.onlyTableData = data
            }
        },
        showAddDialog() {
            this.addUpdateFormOper = 'add'
            this.addUpdateDialogVisible = true
        },
        showUpdateDialog(id) {
            this.addUpdateFormOper = 'edit'
            this.attrId = id
            this.getParamsById(id)
            this.addUpdateDialogVisible = true
        },
        async getParamsById(id) {
            const paramsObj = {
                id: this.cateId,
                attrId: id,
                attr_sel: this.activeName
            }
            const {
                data,
                meta: { msg, status }
            } = await reqParamsById(paramsObj)
            if (200 !== status) return this.$message.error(msg)

            this.addUpdateForm = data
        },

        dialogCancle() {
            this.addUpdateDialogVisible = false
            this.addUpdateForm.attr_name = ''
        },
        dialogOK() {
            this.$refs.addUpdateForm.validate(async (valid) => {
                // 验证有误
                if (!valid) return

                if (this.addUpdateFormOper === 'add') {
                    // 发送添加参数请求
                    const paramsObj = {
                        id: this.cateId,
                        attr_name: this.addUpdateForm.attr_name,
                        attr_sel: this.activeName
                    }
                    const {
                        data,
                        meta: { msg, status }
                    } = await reqAddParams(paramsObj)
                    if (201 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getParamsData()
                    this.addUpdateForm.attr_name = ''
                    this.addUpdateDialogVisible = false
                } else {
                    //发送修改角色请求

                    const paramsObj = {
                        id: this.cateId,
                        attrId: this.attrId,
                        attr_name: this.addUpdateForm.attr_name,
                        attr_sel: this.activeName
                    }
                    const {
                        meta: { msg, status }
                    } = await reqUpdateParamsById(paramsObj)
                    if (200 !== status) return this.$message.error(msg)
                    this.$message.success(msg)
                    this.getParamsData()
                    this.addUpdateDialogVisible = false
                }
            })
        },
        async deleteParams(id) {
            const paramsObj = { id: this.cateId, attrId: id }
            const {
                meta: { msg, status }
            } = await reqDeleteParamsById(paramsObj)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)

            this.getParamsData()
        },
        openDeleteBox(id) {
            this.$confirm('是否删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.deleteParams(id)
                })
                .catch(() => {})
        },
        showInput(row) {
            row.inputVisible = true
            this.$nextTick((_) => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },

        handleInputConfirm(row) {
            let newTag = row.inputValue.trim()
            if (newTag.length === 0) {
                row.inputVisible = false
                return
            }
            if (row.attr_vals.indexOf(newTag) === -1) {
                row.attr_vals.push(newTag)
                this.saveTag(row)
            } else {
                this.$message.error('请勿重复添加')
            }
            row.inputValue = ''
            row.inputVisible = false
        },
        async saveTag(row) {
            console.log(row)
            const paramsObj = {
                id: row.cat_id,
                attrId: row.attr_id,
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(' ')
            }
            const {
                data,
                meta: { msg, status }
            } = await reqUpdateParamsById(paramsObj)
            if (200 !== status) return this.$message.error(msg)
            this.$message.success(msg)
        },
        removeTag(i,row){
             
            // this.openDeleteBox(row.attr_id)
            row.attr_vals.splice(i,1)
            this.saveTag(row)
        }
    }
}
</script>
<style lang="less" scoped>
.el-alert {
    margin: 5px 0;
}
.el-row {
    margin: 15px 0;
}
.rightsTable {
    text-align: center;
}
.el-tag {
    margin: 5px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>